package com.ebb;

import java.util.HashMap;
import java.util.Map;

import org.json.JSONObject;

import android.app.Activity;
import android.app.PendingIntent;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.stackmob.sdk.api.StackMob;
import com.stackmob.sdk.callback.StackMobCallback;
import com.stackmob.sdk.exception.StackMobException;

public class EBBStackMobActivity extends Activity implements OnClickListener {
	private EditText etId;
	private EditText etPwd;
	private Button btnSignIn;
	private Button btnSignUp;
	private Button btnPush;
	private Intent intent;
	private StackMob stackmob;
	private static final String TAG = EBBStackMobActivity.class.getCanonicalName();
	
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
		Log.i(TAG, "#Sign In :: onCreate");

        EBBAlert.setContext(EBBStackMobActivity.this);
        EBBAlert.setDuration(Toast.LENGTH_SHORT);
        
		stackmob = ((EBBStackMobApplication) getApplication()).getStackMobService();
		
//		EBBC2DMRegistrationIDHolder regHolder = new EBBC2DMRegistrationIDHolder(this);
//		if (regHolder.hasID()) {
//			try {
//				Log.i(TAG, "registration ID " + regHolder.getID() + " was already stored in shared prefs");
//				EBBAlert.message(1, null, "registration ID " + regHolder.getID() + " was already stored in shared prefs");
//			}
//			catch (EBBC2DMRegistrationIDHolder.NoStoredRegistrationIDException e) {
//				Log.e(TAG, "failed to get registration ID from shared prefs, even though shared prefs reports that it's there" , e);
//				EBBAlert.message(1, null, "failed to get registration ID from shared prefs, even though shared prefs reports that it's there");
//			}
//		} else {
//			Log.i(TAG, "registration ID was not already stored in shared prefs. fetching a new one and saving it");
//			EBBAlert.message(1, null, "registration ID was not already stored in shared prefs. fetching a new one and saving it");
//			try {
//				requestRegistrationId();
//			} catch (Exception e) {
//				e.printStackTrace();
//			}
//		}
		
		initLayout();
    }
	
	@Override
	protected void onStart() {
		super.onStart();
		Log.i(TAG, "#Sign In :: onStart");
		etId.setText("test");
		etPwd.setText("1234");
	}

	@Override
	protected void onStop() {
		super.onStop();
		Log.i(TAG, "#Sign In :: onStop");
		etId.setText("");
		etPwd.setText("");
	}
    
    private void initLayout() {
		this.etId = (EditText) findViewById(R.id.id_value);
		this.etPwd = (EditText) findViewById(R.id.pwd_value);

		this.btnSignIn = (Button) findViewById(R.id.signin_button);
		this.btnSignUp = (Button) findViewById(R.id.signup_button);
		this.btnPush = (Button) findViewById(R.id.push_button);

		this.btnSignIn.setId(0x1001);
		this.btnSignUp.setId(0x1002);
		this.btnPush.setId(0x1003);

		this.btnSignIn.setOnClickListener(this);
		this.btnSignUp.setOnClickListener(this);
		this.btnPush.setOnClickListener(this);
	}
    
    public void requestRegistrationId() throws Exception {
		try {
			EBBAlert.message(1, null, getRegistrationIDHolder().getID());
		}
		catch(EBBC2DMRegistrationIDHolder.NoStoredRegistrationIDException e) {
			Intent intent = new Intent("com.google.android.c2dm.intent.REGISTER");
			intent.putExtra("app", PendingIntent.getBroadcast(this, 0, new Intent(), 0));
			intent.putExtra("sender", "apexcns.test@gmail.com");
			startService(intent);
		}
	}
	
	private EBBC2DMRegistrationIDHolder getRegistrationIDHolder() {
		return new EBBC2DMRegistrationIDHolder(EBBStackMobActivity.this);
	}
    
	@Override
	public void onClick(View v) {
		String username = etId.getText().toString();
		String password = etPwd.getText().toString();
		switch (v.getId()) {
		case 0x1001: // Sign In
	        Log.i(TAG, "#call sign in");
			if (username.length() > 0 && password.length() > 0) {
				Map<String, String> params = new HashMap<String, String>();
				params.put("username", username);
				params.put("password", password);
				stackmob.login(params, new StackMobCallback() {
                    @Override
                    public void success(String s) {
                        Log.i(TAG, "#login Successed!!!!!!!!");
                        // success login!
                        JSONObject jsonObject;
                        try {
                            jsonObject = new JSONObject(s);
                            
                            EBBUser user = EBBUser.getInstance();
                            user.setUserName(jsonObject.getString("username"));
                            user.setNickName(jsonObject.getString("nickname"));
                            user.setCreateddate(jsonObject.getString("createddate"));
                            user.setLastmoddate(jsonObject.getString("lastmoddate"));
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
    					runOnUiThread(new Runnable() {
    						@Override
    						public void run() {
    							EBBAlert.message(1, null, "Sign In Success!");
    							setIntent("com.ebb.EBBListActivity");
    						}
    					});
                    }
                    
                    @Override
                    public void failure(StackMobException e) {
                        Log.i(TAG, "#login failed");
                        e.printStackTrace();
                    }
                });
			} else {
				EBBAlert.message(0, "Sign In Failure", "Please insert a ID/Password !");
			}
			break;
		case 0x1002: // Sign Up
			setIntent("com.ebb.EBBSignUpActivity");
			break;
		case 0x1003: // Push Message
			setIntent("com.ebb.EBBMessageActivity");
			break;
		}
	}
	
	private void setIntent(String activity) {
		intent = new Intent(activity);
		startActivity(intent);
	}
}